<?php
namespace app\shop\controller\goods\ozon;

use app\common\model\admin\service_config\ServiceConfigData;
use app\common\model\admin\service_config\ServiceConfigTabAccount;
use app\common\model\shop\CategoryModel;
use app\common\model\shop\CurrencyModel;
use app\common\model\shop\GoodsModel;
use app\common\model\shop\ozon\OzonGoodsAttributeModel;
use app\common\model\shop\ozon\OzonGoodsCategoryModel;
use app\common\model\shop\ozon\OzonGoodsFeatureModel;
use app\common\model\shop\ozon\OzonGoodsImageModel;
use app\common\model\shop\ozon\OzonGoodsModel;
use app\common\model\shop\ozon\OzonGoodsPushMsgModel;
use app\common\model\shop\ozon\OzonGoodsSkuModel;
use app\common\model\shop\ozon\OzonGoodsSkuStockModel;
use app\common\model\shop\ozon\OzonWarehouseModel;
use app\common\model\shop\PlatformModel;
use app\common\model\shop\ShopsModel;
use app\common\service\fanyi\BaiduFaiyi;
use app\common\service\shop\Ozon;
use app\common\service\shop\SyncGoodService;
use think\admin\Controller;
use think\admin\helper\QueryHelper;
use think\admin\model\SystemBase;
use think\admin\model\SystemUser;
use think\App;
use think\facade\Db;
use think\facade\Validate;

/**
 * OZON商品管理
 * @package app\admin\controller\goods\ozon
 * @author xuli
 * @DateTime 2024-10-29 14:10
 */
class Goods extends Controller
{

    public $platform_id = 0;
    public function __construct(App $app)
    {
        parent::__construct($app);
        $platform_info = PlatformModel::where('code', 'ozon')->find();
        $this->platform_id = $platform_info['id'] ?? 0;
    }

    /**
     * 商品列表
     * @auth true
     * @menu true
     * @author xuli
     * @DateTime 2024-10-29 14:10
     * @return void
     */
    public function index()
    {
        OzonGoodsModel::mQuery()->layTable(function () {
            $this->title = '商品管理';
            // 订单来源
            $this->from_arr = OzonGoodsModel::from_arr();
            // 用户列表
            $user_list = SystemUser::getUserList($this->account_id, SystemUser::getNoTeacherUserType());
            $this->system_user = array_column($user_list, 'nickname', 'id');
            // 店铺列表
            $map = [
                ['is_deleted',  '=', 0]
            ];
            if(!empty($this->account_id)){
                $map[] = ['account_id', '=', $this->account_id];
            }
            $this->shop_list = ShopsModel::mk()->where($map)->column('id,name');
            // 推送状态
            $this->push_status_arr = OzonGoodsModel::pushStatusArr();

        }, function (QueryHelper $query) {

            //$this->check_user = false;
            $query->with(['userName','updateName','skuList' => function($sku) {
                $sku->field('id,title,goods_nu,goods_id,attribute_titles,sale_price,push_status,price');
            }]);

            $query->where('is_deleted', 0);

            $query->like('title,source_url#collect_url')->equal('account_id,from_type#from,user_id,update_user_id,spu_code,shop_id,push_status')->dateBetween('create_at,update_at');
            $query->order('id desc');
        });
    }

    protected function _index_page_filter(&$data)
    {
        // 获取店铺信息
        $shop_ids = array_column($data, 'shop_id');
        $shop_data = [];
        if(!empty($shop_ids)){
            $shop_data = ShopsModel::mk()->whereIn('id', $shop_ids)->column('id,name', 'id');
        }
        // 获取分类信息
        $shop_category_ids = array_column($data, 'shop_category_id');
        $shop_category_data = [];
        if(!empty($shop_category_ids)){
            $shop_category_data = CategoryModel::mk()->whereIn('id', $shop_category_ids)->column('id,name', 'id');
        }
        // 推送状态集合
        $push_status_arr = OzonGoodsModel::pushStatusArr();
        $sku_push_status_arr = OzonGoodsSkuModel::pushStatusArr();
        foreach ($data as &$v) {
            // 来源
            $v['from_text'] = OzonGoodsModel::from_arr()[$v['from_type']];
            // 店铺名称
            $v['shop_name'] = !empty($shop_data[$v['shop_id']]['name']) ? $shop_data[$v['shop_id']]['name'] : '';
            // 分类名称
            $v['shop_category_name'] = !empty($shop_category_data[$v['shop_category_id']]['name']) ? $shop_category_data[$v['shop_category_id']]['name'] : '';
            // 推送状态
            $v['push_status_text'] = $push_status_arr[$v['push_status']];
            // sku推送状态
            $v['sku_push_arr'] = $sku_push_status_arr;
        }
    }

    /**
     * 添加
     * @auth true
     * @menu true
     * @return void
     */
    public function add()
    {
        if($this->request->isPost()) {
            $params = $this->request->post();
            // 验证
            $this->_vali([
                'shop_id.require'     => lang('分类名称不能为空'),
                'title.require'       => lang('产品名称不能为空'),
                'title.length:1,200'  => lang('产品名称长度不能超过100'),
                'category_id.require' => lang('平台分类不能为空'),
                'vat_type.require'  => lang('VAT不能为空'),
                'account_id.require'  => lang('公司不能为空')
            ]);

            $goods_images = $params['goods_images'] ?? '';
            $main_pic = '';
            if($goods_images) {
                $goods_images = explode('|', $goods_images);
                $main_pic = $goods_images[0];
            }

            // 获取分类必填属性特征
            $category_id = $params['category_id'] ?? 0;
            $attr_value = '';
            if($category_id) {
                $required_ids = OzonGoodsFeatureModel::mq()->where(['category_id' => $category_id, 'is_required' => 1])->column('name', 'feature_id');
                // 分类属性特征
                $input_value_list = $params['input_value_list'] ?? [];
                $select_value_list = $params['select_value_list'] ?? [];
                $value_list = $input_value_list + $select_value_list;
                unset($input_value_list);
                unset($select_value_list);
                // 获取映射属性
                $mapping_spec = $params['mapping_spec'] ?? [];
                $mapping_spec_data = array_flip($mapping_spec);
                $attr_value = json_encode($value_list);
                $value_list = $value_list + $mapping_spec_data;
                foreach ($required_ids as $k => $v) {
                    if(empty($value_list[$k])) {
                        $this->error($v . '不能为空');
                    }
                }
            }

             // 校验sku信息
             $rule = [
                'goods_nu|SKU'  => 'require|length:1,50',
                'barcode|条码'  => 'length:1,100',
                'price|售价'   => 'require|float|between:0.01,10000000',
                'sale_price|原价' => 'require|float|between:0.01,10000000',
                // 'stock|库存'       =>  'require|integer|between:1,1000000',
                'length|长'         =>  'require|float|between:0.01,1000000',
                'width|宽'          =>  'require|float|between:0.01,1000000',
                'height|高'         =>  'require|float|between:0.01,1000000',
                'weight|重量'       =>  'require|float|between:0.01,1000000',
            ];
            if($params['mode_type'] == 1){
                if(empty($params['skus'])){
                    $this->error('请至少添加一条SKU信息');
                }
                // 校验sku属性映射
                if(empty($params['mapping_spec']) || empty($params['mapping_spec_value'])){
                    $this->error('SKU属性映射不能为空');
                }
                foreach ($params['mapping_spec'] as $k => $v) {
                    if(empty($v)){
                        $this->error('SKU属性映射项不能为空');
                    }
                    foreach ($params['mapping_spec_value'][$k] as $s_k => $s_v) {
                        if(empty($s_v)){
                            $this->error('SKU属性映射值不能为空');
                        }
                    }
                }
                // 获取sku是否存在
                $goods_nu_arr = array_column($params['skus'], 'goods_nu');
                $map = [
                    ['goods_nu', 'in', $goods_nu_arr]
                ];
                $exist_sku_data = OzonGoodsSkuModel::mk()->where($map)->column('id', 'goods_nu');
                $unique_sku = [];
                $validate = Validate::rule($rule);
                foreach ($params['skus'] as $key => $sku_info) {
                    if (!$validate->check($sku_info)) {
                        $this->error($key.$validate->getError());
                    }
                    if(isset($unique_sku[$sku_info['goods_nu']])){
                        $this->error($sku_info['goods_nu'].'SKU与上面重复了');
                    }
                    if(!empty($exist_sku_data[$sku_info['goods_nu']])){
                        $this->error($sku_info['goods_nu'].'SKU已存在');
                    }
                    $unique_sku[$sku_info['goods_nu']] = 1;
                }
            }else{
                $validate = Validate::rule($rule);
                if (!$validate->check($params['sku'])) {
                    $this->error($validate->getError());
                }
                // 校验sku是否唯一
                $map = [
                    ['goods_nu', '=', $params['sku']['goods_nu']]
                ];
                $count = OzonGoodsSkuModel::mk()->where($map)->count();
                if($count > 0){
                    $this->error($params['sku']['goods_nu'].'SKU已存在');
                }
            }

            $goods_data = [
                'user_id' => $this->adminUser['id'],
                'update_user_id' => $this->adminUser['id'],
                'account_id' => $params['account_id'] ?? 0,
                'spu_code' => $params['spu_code'], // SPU商品编码
                'title' => $params['title'],
                'main_pic' => $main_pic,
                'short_desc' => $params['short_desc'] ?? '', // 商品简介
                'long_desc' => $params['long_desc'] ?? '', // 商品内容
                'shop_id' => $params['shop_id'] ?? 0,
                'category_id' => $params['category_id'] ?? 0, // 平台分类ID
                'brand_id' => $params['brand_id'] ?? 0, // 品牌
                'mode_type' => $params['mode_type'] ?? 0, // 库存类型
                'source_url' => $params['source_url'] ?? '', // 货源地址
                'from_type' => 2, // 来源类型 1：数据采集  2手工创建
                'shop_category_id' => $params['shop_category_id'] ?? 0,
                'vat_type'      => $params['vat_type'] ?? 0,// vat
                'feature_value' => $attr_value // 属性特征值
            ];

            // 获取店铺信息
            $shop_info = ShopsModel::mq()->find($goods_data['shop_id']);
            // 获取币种信息
            $currency_info = CurrencyModel::mk()->find($shop_info['currency_id'] ?? 0);

            // 启动事务
            Db::startTrans();
            try {
                $goods_id = OzonGoodsModel::mq()->insertGetId($goods_data);

                // 处理规格属性
                $specData = [];
                if(!empty($params['specData'])) {
                    foreach ($params['specData'] as $v) {
                        $feature_id = $params['mapping_spec'][$v['id']] ?? 0;
                        $feature_value = $params['mapping_spec_value'][$v['id']] ?? [];
                        foreach ($v['child'] as $vv) {
                            $specData[] = [
                                'goods_id' => $goods_id,
                                'feature_id' => $feature_id,
                                'value' => $feature_value[$vv['id']] ?? 0,
                                'key_name' => $v['title'],
                                'value_name' => $vv['title'],
                                'checked' => ($vv['checked'] == 'true' || $vv['checked'] == '1') ? 1 : 0,
                            ];
                        }
                    }

                    $specTitleId = []; // 规格值 => id 对应关系
                    foreach ($specData as $v) {
                        $specTitleId[$v['value_name']] = OzonGoodsAttributeModel::mq()->insertGetId($v);
                    }
                }

                $goods_skus = [];
                if($goods_data['mode_type'] == 1) {
                    // 处理SKU
                    if(!empty($params['skus']) && !empty($specData)) {
                        foreach ($params['skus'] as $k => $v) {
                            // 处理attribute_ids
                            $attribute_ids_arr = explode(',',$k);
                            foreach ($attribute_ids_arr as &$attribute_v) {
                                $attribute_v = $specTitleId[$attribute_v] ?? '';
                            }
                            $attribute_ids = implode(',',$attribute_ids_arr);
                            $goods_skus[] = [
                                'title' => $goods_data['spu_code'].'_'.$k,
                                'goods_id' => $goods_id,
                                'goods_nu'  => $v['goods_nu'],
                                'barcode'   => $v['barcode'],
                                'image' => $v['image'],
                                'price' => $v['price'],
                                'sale_price'    => $v['sale_price'],
                                'length' => $v['length'],
                                'width' => $v['width'],
                                'height' => $v['height'],
                                'weight' => $v['weight'],
                                // 'stock' => $v['stock'],
                                'volume' => round($v['length'] * $v['width'] * $v['height'],3),
                                'attribute_titles' => $k,
                                'attribute_ids' => $attribute_ids,
                                'currency_id' => $currency_info['id'] ?? 0,
                                'currency_rate' => $currency_info['exchange_rate'] ?? 0
                            ];
                        }
                    }
                } else {
                    $goods_skus[] = [
                        'title' => $goods_data['spu_code'],
                        'goods_id' => $goods_id,
                        'goods_nu' => $params['sku']['goods_nu'] ?? '',
                        'barcode' => $params['sku']['barcode'] ?? '',
                        'price' => $params['sku']['price'] ?? 0,
                        'sale_price' => $params['sku']['sale_price'] ?? 0,
                        'length' => $params['sku']['length'] ?? 0,
                        'width' => $params['sku']['width'] ?? 0,
                        'height' => $params['sku']['height'] ?? 0,
                        'weight' => $params['sku']['weight'] ?? 0,
                        // 'stock' => $params['sku']['stock'] ?? 0,
                        'volume' => round($params['sku']['length'] * $params['sku']['width'] * $params['sku']['height'],3),
                        'image'  => $main_pic,
                        'currency_id' => $currency_info['id'] ?? 0,
                        'currency_rate' => $currency_info['exchange_rate'] ?? 0
                    ];
                }
                if($goods_skus) {
                    // 添加sku表
                    OzonGoodsSkuModel::mq()->insertAll($goods_skus);
                }

                // 处理商品图片
                $image_data = [];
                if($goods_images) {
                    foreach ($goods_images as $v) {
                        $image_data[] = [
                            'goods_id' => $goods_id,
                            'image' => $v,
                        ];
                    }
                    // 插入商品图片
                    OzonGoodsImageModel::mq()->insertAll($image_data);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 0, 'info' => $e->getMessage()]);
            }
            $this->success('保存成功');
        }

        // 获取系统分类
        $category_where = [
            ['status', '=', 1],
        ];
        $shop_category_list = CategoryModel::mq()->where($category_where)->order('level')->field('name title,id,pid,path')->select()->toArray();
        $this->shop_category_list = CategoryModel::categoryTree($shop_category_list);

        // vat列表
        $this->vat_list = OzonGoodsModel::getVatList();

        $this->shop_account = $this->account_id;

        OzonGoodsModel::mForm();
    }


    /**
     * 编辑
     * @auth true
     * @menu true
     * @return void
     */
    public function edit()
    {
        $this->goods_id = $this->request->param('id', 0);
        if($this->request->isPost()) {
            $params = $this->request->post();
            // 验证
            $this->_vali([
                'shop_id.require'     => lang('分类名称不能为空'),
                'title.require'       => lang('产品名称不能为空'),
                'title.length:1,200'  => lang('产品名称长度不能超过200'),
                'category_id.require' => lang('平台分类不能为空'),
                'vat_type.require'  => lang('VAT不能为空'),
                'account_id.require'  => lang('公司不能为空')
            ]);

            // 处理图片
            $goods_images = $params['goods_images'] ?? '';
            $main_pic = '';
            if($goods_images) {
                $goods_images = explode('|', $goods_images);
                $main_pic = $goods_images[0];
            }

            // 获取分类必填属性特征
            $category_id = $params['category_id'] ?? 0;
            $attr_value = [];
            if($category_id) {
                $required_ids = OzonGoodsFeatureModel::mq()->where(['category_id' => $category_id, 'is_required' => 1])->column('name', 'feature_id');
                // 分类属性特征
                $input_value_list = $params['input_value_list'] ?? [];
                $select_value_list = $params['select_value_list'] ?? [];
                $value_list = $input_value_list + $select_value_list;
                unset($input_value_list);
                unset($select_value_list);
                // 获取映射属性
                $mapping_spec = $params['mapping_spec'] ?? [];
                $mapping_spec_data = array_flip($mapping_spec);
                $attr_value = json_encode($value_list);
                $value_list = $value_list + $mapping_spec_data;
                foreach ($required_ids as $k => $v) {
                    if(empty($value_list[$k])) {
                        $this->error($v . '不能为空');
                    }
                }
            } else {
                $attr_value = json_encode($attr_value);
            }

            // 校验sku信息
            $rule = [
                'goods_nu|SKU'  => 'require|length:1,50',
                'barcode|条码'  => 'length:1,100',
                'price|售价'   => 'require|float|between:0.01,10000000',
                'sale_price|原价' => 'require|float|between:0.01,10000000',
                // 'stock|库存'       =>  'require|integer|between:1,1000000',
                'length|长'         =>  'require|float|between:0.01,1000000',
                'width|宽'          =>  'require|float|between:0.01,1000000',
                'height|高'         =>  'require|float|between:0.01,1000000',
                'weight|重量'       =>  'require|float|between:0.01,1000000',
            ];
            if($params['mode_type'] == 1){
                if(empty($params['skus'])){
                    $this->error('请至少添加一条SKU信息');
                }
                // 校验sku属性映射
                if(empty($params['mapping_spec']) || empty($params['mapping_spec_value'])){
                    $this->error('SKU属性映射不能为空');
                }
                foreach ($params['mapping_spec'] as $k => $v) {
                    if(empty($v)){
                        $this->error('SKU属性映射项不能为空');
                    }
                    foreach ($params['mapping_spec_value'][$k] as $s_k => $s_v) {
                        if(empty($s_v)){
                            $this->error('SKU属性映射值不能为空');
                        }
                    }
                }
                // 获取sku是否存在
                $goods_nu_arr = array_column($params['skus'], 'goods_nu');
                $map = [
                    ['goods_nu', 'in', $goods_nu_arr],
                    ['goods_id', '<>', $this->goods_id]
                ];
                $exist_sku_data = OzonGoodsSkuModel::mk()->where($map)->column('id', 'goods_nu');
                $unique_sku = [];
                $validate = Validate::rule($rule);
                foreach ($params['skus'] as $key => $sku_info) {
                    if (!$validate->check($sku_info)) {
                        $this->error($key.$validate->getError());
                    }
                    if(isset($unique_sku[$sku_info['goods_nu']])){
                        $this->error($sku_info['goods_nu'].'SKU与上面重复了');
                    }
                    if(!empty($exist_sku_data[$sku_info['goods_nu']])){
                        $this->error($sku_info['goods_nu'].'SKU已存在');
                    }
                    $unique_sku[$sku_info['goods_nu']] = 1;
                }
            }else{
                $validate = Validate::rule($rule);
                if (!$validate->check($params['sku'])) {
                    $this->error($validate->getError());
                }
                // 校验sku是否唯一
                $map = [
                    ['goods_nu', '=', $params['sku']['goods_nu']],
                    ['goods_id', '<>', $this->goods_id] // 排除自身
                ];
                $count = OzonGoodsSkuModel::mk()->where($map)->count();
                if($count > 0){
                    $this->error($params['sku']['goods_nu'].'SKU已存在');
                }
            }
            

            $goods_data = [
                'user_id' => $this->adminUser['id'],
                'update_user_id' => $this->adminUser['id'],
                'account_id' => $params['account_id'] ?? 0,
                'spu_code' => $params['spu_code'], // SPU商品编码
                'title' => $params['title'],
                'main_pic' => $main_pic,
                'short_desc' => $params['short_desc'] ?? '', // 商品简介
                'long_desc' => $params['long_desc'] ?? '', // 商品内容
                'shop_id' => $params['shop_id'] ?? 0,
                'category_id' => $params['category_id'] ?? 0, // 平台分类ID
                'brand_id' => $params['brand_id'] ?? 0, // 品牌
                'mode_type' => $params['mode_type'] ?? 0, // 库存类型
                'source_url' => $params['source_url'] ?? '', // 货源地址
                'from_type' => 2, // 来源类型 1：数据采集  2手工创建
                'shop_category_id' => $params['shop_category_id'] ?? 0,
                'vat_type'      => $params['vat_type'] ?? 0,// vat
                'feature_value' => $attr_value // 属性特征值
            ];

            // 获取店铺信息
            $shop_info = ShopsModel::mq()->find($goods_data['shop_id']);
            // 获取币种信息
            $currency_info = CurrencyModel::mq()->find($shop_info['currency_id'] ?? 0);
            // 获取sku信息
            $map = [
                ['goods_id', '=', $this->goods_id]
            ];
            $old_sku_data = OzonGoodsSkuModel::mk()->where($map)->column('id', 'goods_nu');

            // 启动事务
            Db::startTrans();
            try {
                // 删除图片
                OzonGoodsImageModel::mq()->where(['goods_id' => $this->goods_id])->delete();
                // 删除规格
                OzonGoodsAttributeModel::mq()->where(['goods_id' => $this->goods_id])->delete();
                // // 删除规格
                // OzonGoodsSkuModel::mq()->where(['goods_id' => $this->goods_id])->delete();
                // 更新产品
                OzonGoodsModel::mq()->where(['id' => $this->goods_id])->update($goods_data);

                // 处理规格属性
                $specData = [];
                if(!empty($params['specData'])) {
                    foreach ($params['specData'] as $v) {
                        $feature_id = $params['mapping_spec'][$v['id']] ?? 0;
                        $feature_value = $params['mapping_spec_value'][$v['id']] ?? [];
                        foreach ($v['child'] as $vv) {
                            $specData[] = [
                                'goods_id' => $this->goods_id,
                                'feature_id' => $feature_id,
                                'value' => $feature_value[$vv['id']] ?? '',
                                'key_name' => $v['title'],
                                'value_name' => $vv['title'],
                                'checked' => ($vv['checked'] == 'true' || $vv['checked'] == '1') ? 1 : 0,
                            ];
                        }
                    }

                    $specTitleId = []; // 规格值 => id 对应关系
                    foreach ($specData as $v) {
                        $specTitleId[$v['value_name']] = OzonGoodsAttributeModel::mq()->insertGetId($v);
                    }
                }

                $goods_skus = [];
                if($goods_data['mode_type'] == 1) {
                    // 处理SKU
                    if(!empty($params['skus']) && !empty($specData)) {
                        // 获取删除的sku
                        $delete_sku_ids = array_diff_key($old_sku_data, array_column($params['skus'], 'goods_nu', 'goods_nu'));
                        if(!empty($delete_sku_ids)){
                            OzonGoodsSkuModel::mq()->where('id', 'in', $delete_sku_ids)->delete();
                        }
                        foreach ($params['skus'] as $k => $v) {
                            // 处理attribute_ids
                            $attribute_ids_arr = explode(',',$k);
                            foreach ($attribute_ids_arr as &$attribute_v) {
                                $attribute_v = $specTitleId[$attribute_v] ?? '';
                            }
                            $attribute_ids = implode(',',$attribute_ids_arr);
                            $temp_sku = [
                                'goods_id' => $this->goods_id,
                                'goods_nu'  => $v['goods_nu'],
                                'barcode' => $v['barcode'] ?? '',
                                'image' => $v['image'],
                                'price' => $v['price'],
                                'sale_price' => $v['sale_price'],
                                'length' => $v['length'],
                                'width' => $v['width'],
                                'height' => $v['height'],
                                'weight' => $v['weight'],
                                // 'stock' => $v['stock'],
                                'volume' => round($v['length'] * $v['width'] * $v['height'],3),
                                'attribute_titles' => $k,
                                'attribute_ids' => $attribute_ids,
                                'currency_id' => $currency_info['id'] ?? 0,
                                'currency_rate' => $currency_info['exchange_rate'] ?? 0
                            ];
                            if(!empty($old_sku_data[$v['goods_nu']])){
                                $edit_id = $old_sku_data[$v['goods_nu']];
                                OzonGoodsSkuModel::mq()->where(['id' => $edit_id])->update($temp_sku);
                            }else{
                                $goods_skus[] = $temp_sku;
                            } 
                        }
                    }
                } else {
                    $temp_sku = [
                        'goods_id' => $this->goods_id,
                        'goods_nu' => $params['sku']['goods_nu'] ?? '',
                        'barcode' => $params['sku']['barcode'] ?? '',
                        'price' => $params['sku']['price'] ?? 0,
                        'sale_price' => $params['sku']['sale_price'] ?? 0,
                        'length' => $params['sku']['length'] ?? 0,
                        'width' => $params['sku']['width'] ?? 0,
                        'height' => $params['sku']['height'] ?? 0,
                        'weight' => $params['sku']['weight'] ?? 0,
                        // 'stock' => $params['sku']['stock'] ?? 0,
                        'volume' => round($params['sku']['length'] * $params['sku']['width'] * $params['sku']['height'],3),
                        'image'  => $main_pic,
                        'currency_id' => $currency_info['id'] ?? 0,
                        'currency_rate' => $currency_info['exchange_rate'] ?? 0
                    ];
                    $edit_id = current($old_sku_data);
                    OzonGoodsSkuModel::mq()->where(['id' => $edit_id])->update($temp_sku);
                }
                if($goods_skus) {
                    // 添加sku表
                    OzonGoodsSkuModel::mq()->insertAll($goods_skus);
                }

                // 处理商品图片
                $image_data = [];
                if($goods_images) {
                    foreach ($goods_images as $v) {
                        $image_data[] = [
                            'goods_id' => $this->goods_id,
                            'image' => $v,
                        ];
                    }
                    // 插入商品图片
                    OzonGoodsImageModel::mq()->insertAll($image_data);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 0, 'info' => $e->getMessage()]);
            }
            $this->success('保存成功');
        }

        // 商品信息
        $this->goods_info = OzonGoodsModel::mq()->find($this->goods_id);

        // 获取系统分类
        $category_where = [
            ['status', '=', 1],
        ];
        $shop_category_list = CategoryModel::mq()->where($category_where)->order('level')->field('name title,id,pid,path')->select()->toArray();
        $this->shop_category_list = CategoryModel::categoryTree($shop_category_list);

        // // 获取平台分类列表
        // $ozon_goods_model = new OzonGoodsModel();
        // $this->category_list = $ozon_goods_model->getCategoryList($this->goods_info['shop_id']);

        // 获取店铺列表
        $this->shop_list = ShopsModel::mq()->where(['user_id' => $this->adminUser['id'], 'is_deleted' => 0, 'platform_id' => $this->platform_id])->column('name', 'id');

        $specDataTree = $goods_skus_data = [];

        // 获取sku
        $feature_list = []; // 映射属性
        if($this->goods_info['mode_type'] == 0) { // 单品
            $this->sku_info = OzonGoodsSkuModel::mq()->where(['goods_id' => $this->goods_id])->find();
        } else { // 多品
            //  商品规格
            $specData = OzonGoodsAttributeModel::mq()->where(['goods_id' => $this->goods_id])->select()->toArray();
            // 处理结构
            foreach ($specData as $k => $v){
                $specDataTree[$v['key_name']]['id'] = $v['key_name'];
                $specDataTree[$v['key_name']]['title'] = $v['key_name'];
                $specDataTree[$v['key_name']]['child'][] = [
                    'id' => $v['value_name'],
                    'title' => $v['value_name'],
                    'checked' => $v['checked'],
                ];
                $feature_list['origin_spec'][$v['key_name']] = $v['key_name']; // 原始规格项
                $feature_list['mapping_spec'][$v['key_name']] = $v['feature_id']; // 映射规格项
                $feature_list['origin_spec_value'][$v['key_name']][$v['value_name']] = $v['value_name']; // 原始规格值
                $feature_list['mapping_spec_value'][$v['key_name']][$v['value_name']] = $v['value']; // 映射规格值
            }

            $specDataTree = array_values($specDataTree);
            // skus todo
            $goods_skus = OzonGoodsSkuModel::mq()->where(['goods_id' => $this->goods_id])->select()->toArray();
            $goods_skus_data = [];
            foreach ($goods_skus as $v){
                $goods_skus_data["skus[" . $v['attribute_titles'] . "][image]"] = $v['image'];
                // $goods_skus_data["skus[" . $v['attribute_titles'] . "][title]"] = $v['title'];
                $goods_skus_data["skus[" . $v['attribute_titles'] . "][barcode]"] = $v['barcode'];
                $goods_skus_data["skus[" . $v['attribute_titles'] . "][price]"] = $v['price'];
                $goods_skus_data["skus[" . $v['attribute_titles'] . "][sale_price]"] = $v['sale_price'];
                $goods_skus_data["skus[" . $v['attribute_titles'] . "][length]"] = $v['length'];
                $goods_skus_data["skus[" . $v['attribute_titles'] . "][width]"] = $v['width'];
                $goods_skus_data["skus[" . $v['attribute_titles'] . "][height]"] = $v['height'];
                $goods_skus_data["skus[" . $v['attribute_titles'] . "][weight]"] = $v['weight'];
                $goods_skus_data["skus[" . $v['attribute_titles'] . "][goods_nu]"] = $v['goods_nu'];
                $goods_skus_data["skus[" . $v['attribute_titles'] . "][stock]"] = $v['stock'];
            }
        }
        $this->specDataTree = json_encode($specDataTree ?? []);
        $this->goods_skus_data = json_encode($goods_skus_data ?? []);
        $this->feature_data = json_encode($feature_list ?? []);

        //  商品规格
        $GoodsImages = OzonGoodsImageModel::mq()->where(['goods_id' => $this->goods_id])->column('image');
        $this->goods_images = implode('|',$GoodsImages);

        $this->shop_account = !empty($this->goods_info['account_id']) ? $this->goods_info['account_id'] : $this->account_id;
        // vat列表
        $this->vat_list = OzonGoodsModel::getVatList();

        OzonGoodsModel::mForm();
    }

    /**
     * 获取商品SPU
     * @return void
     */
    public function createSPU()
    {
        // 获取
        $spu_code = OzonGoodsModel::mk()->createSPU();
        $this->success('', (string)$spu_code);
    }


    /**
     * 翻译
     *
     * @Description
     * @auth true
     * @author wangqinghui
     * @date 2024-11-05 17:21
     * @return void
     */
    public function translate()
    {
        if($this->request->isPost()){
            $post_data = $this->request->post();
            $rules = [
                'from_lang|原始语言'    =>  'require',
                'to_lang|目标语言'      =>  'require|different:from_lang',
                'ids|商品ID'      =>  'require',
                'account_id|公司ID'     => 'require|number'
            ];
            $rule = Validate::rule($rules);
            if(!$rule->check($post_data)){
                $this->error($rule->getError());
            }
            $goods_id_arr = explode(',', $post_data['ids']);
            if(empty($goods_id_arr)){
                $this->error('请选择需要翻译的商品');
            }
            // 获取需要翻译的模块
            $transfer_part_data = GoodsModel::getTranslatePart();
            $transfer_data = $transfer_part_data['common'] ?? [];
            $transfer_data = array_merge($transfer_data, $post_data['trans_ext'] ?? []);

            $map = [
                ['id', 'in', $goods_id_arr],
                ['is_deleted', '=', 0],
            ];
            $goods_list = OzonGoodsModel::mq()->where($map)->select()->toArray();
            if(empty($goods_list)){
                $this->error('请选择需要翻译的商品');
            }
            if(!empty($transfer_data['is_sku'])){
                // 获取商品属性信息
                $map = [
                    ['goods_id',    'in',   $goods_id_arr],
                ];
                $goods_attr_list = OzonGoodsAttributeModel::mq()->where($map)->select()->toArray();
                $goods_attr_data = [];
                if(!empty($goods_attr_list)){
                    foreach ($goods_attr_list as $goods_attr_info) {
                        $goods_attr_data[$goods_attr_info['goods_id']][] = $goods_attr_info;
                    }
                }
                // 获取商品sku信息
                $goods_sku_list = OzonGoodsSkuModel::mq()->field('id,goods_id,attribute_ids,attribute_titles')->where($map)->select()->toArray();
                $goods_sku_data = [];
                if(!empty($goods_sku_list)){
                    foreach ($goods_sku_list as $goods_sku_info) {
                        $goods_sku_data[$goods_sku_info['goods_id']][] = $goods_sku_info;
                    }
                }
            }

            // 获取翻译平台信息
            $fanyi_data = $fanyi_type_data = [];
            if(!empty($post_data['account_id'])){
                $map = [
                    ['account_id',        '=',  $post_data['account_id']],
                    ['type',              '=',  'fanyi'],
                    ['status',            '=',  1],
                ];
                $fanyi_type_list = ServiceConfigTabAccount::mk()->where($map)->column('id,group');
                if(empty($fanyi_type_list)){
                    $this->error('请先配置翻译平台');
                }
                $fanyi_api_type = GoodsModel::getTranslateApiArr();
                $diff_fanyi = array_diff(array_column($fanyi_type_list, 'group'), array_keys($fanyi_api_type));
                if(!empty($diff_fanyi)){
                    $this->error('有暂不支持的翻译平台');
                }
                $fanyi_type_data = $fanyi_type_list[0];
                $map = [
                    ['account_group_id',    '=',  $fanyi_type_data['id']],
                    ['account_id',          '=',  $post_data['account_id']]
                ];
                $fanyi_data = ServiceConfigData::mk()->where($map)->column('value', 'code');
            }
            if(empty($fanyi_data)){
                $this->error('请先配置翻译平台');
            }
            $trans_obj = null;
            switch ($fanyi_type_data['group']){
                case 'baidu_translate':// 百度翻译
                    // 翻译
                    $config = [
                        'fromLang'  =>      $post_data['from_lang'],
                        'toLang'    =>      $post_data['to_lang'],
                        'appid'     =>      $fanyi_data['appid']  ?? '',
                        'appkey'    =>      $fanyi_data['appkey'] ?? '',
                    ];
                    $trans_obj = new BaiduFaiyi($config);
                    break;
                default:
                    $this->error('暂不支持的翻译平台');
                    break;

            }
            
            foreach ($goods_list as $key => $goods_info) {
                $update_goods_data = [];
                // 开启事务
                Db::startTrans();
                try {
                    foreach ($transfer_data as $t_k => $item) {
                        // 翻译sku规格
                        if(!empty($t_k) && ($t_k == 'is_sku')){
                            // 翻译规格
                            $goods_attr_info = !empty($goods_attr_data[$goods_info['id']]) ? $goods_attr_data[$goods_info['id']] : [];
                            $fan_goods_attr_arr = $fan_goods_key_arr = [];
                            if(!empty($goods_attr_info)){
                                foreach ($goods_attr_info as $goods_attr_item) {
                                    $update_attr_data = [];
                                    if(empty($fan_goods_key_arr[$goods_attr_item['key_name']])){
                                        $trans_res = $trans_obj->fanyi($goods_attr_item['key_name']);
                                        $trans_err = $trans_obj->getErr();
                                        if(!empty($trans_err['error_code'])){
                                            throw new \Exception('属性名称翻译失败:'.$trans_err['error_msg'] ?? '');
                                        }else{
                                            $update_attr_data['key_name'] = implode("\n", $trans_res);
                                        }
                                        $fan_goods_key_arr[$goods_attr_item['key_name']] = $update_attr_data['key_name'];
                                    }else{
                                        $update_attr_data['key_name'] = $fan_goods_key_arr[$goods_attr_item['key_name']];
                                    }
                                    $trans_res = $trans_obj->fanyi($goods_attr_item['value_name']);
                                    $trans_err = $trans_obj->getErr();
                                    if(!empty($trans_err['error_code'])){
                                        throw new \Exception('属性值翻译失败:'.$trans_err['error_msg'] ?? '');
                                    }else{
                                        $update_attr_data['value_name'] = implode("\n", $trans_res);
                                    }
                                    $fan_goods_attr_arr[$goods_attr_item['id']] = $update_attr_data['value_name'];
                                    // 记录翻译前的原始数据
                                    $update_attr_data['origional_key_name'] = $goods_attr_item['key_name'];
                                    $update_attr_data['origional_value_name'] = $goods_attr_item['value_name'];
                                    $count = OzonGoodsAttributeModel::mq()->where(['id' => $goods_attr_item['id']])->update($update_attr_data);
                                    if($count <= 0){
                                        throw new \Exception('更新属性翻译失败');
                                    }
                                }
                            }
                            // 翻译sku
                            $goods_sku_info =!empty($goods_sku_data[$goods_info['id']]) ? $goods_sku_data[$goods_info['id']] : [];
                            if(!empty($goods_sku_info)){
                                foreach ($goods_sku_info as $goods_sku_item) {
                                    $update_sku_data = [];
                                    $attribute_ids = $goods_sku_item['attribute_ids'];
                                    $attribute_ids_arr = explode(',', $attribute_ids);
                                    $attribute_titles = [];
                                    foreach ($attribute_ids_arr as $key => $value) {
                                        $attribute_titles[] = !empty($fan_goods_attr_arr[$value]) ? $fan_goods_attr_arr[$value] : '';
                                    }
                                    $update_sku_data['attribute_titles'] = implode(',', $attribute_titles);
                                    // 记录翻译前的原始数据
                                    $update_sku_data['origional_attribute_titles'] = $goods_sku_item['attribute_titles'];
                                    $count = OzonGoodsSkuModel::mq()->where(['id' => $goods_sku_item['id']])->update($update_sku_data);
                                    if($count <= 0){
                                        throw new \Exception('更新sku翻译失败');
                                    }
                                }
                            }
                        }else{
                            $t_field = !empty(explode('is_', $t_k)[1]) ? explode('is_', $t_k)[1] : '';
                            if(empty($t_field)){
                                continue;
                            }
                            if(!empty($goods_info[$t_field])){
                                if($t_field == 'long_desc'){
                                    // 提取汉字
                                    preg_match_all('/[\x{4e00}-\x{9fa5}]+/u', $goods_info[$t_field], $matches);
                                    // 获取所有汉字
                                    if(!empty($matches[0])){
                                        $long_desc_str = implode("\n", $matches[0]);
                                        $trans_res = $trans_obj->fanyi($long_desc_str);
                                        $trans_err = $trans_obj->getErr();
                                        if(!empty($trans_err['error_code'])){
                                            throw new \Exception($t_field.'翻译失败:'.$trans_err['error_msg'] ?? '');
                                        }else{
                                            $update_goods_data[$t_field] = str_replace($matches[0], $trans_res, $goods_info[$t_field]);
                                            // 记录翻译前的原始数据
                                            $update_goods_data['origional_'.$t_field] = $goods_info[$t_field];
                                        }
                                    }
                                }else{
                                    $trans_res = $trans_obj->fanyi($goods_info[$t_field]);
                                    $trans_err = $trans_obj->getErr();
                                    if(!empty($trans_err['error_code'])){
                                        throw new \Exception($t_field.'翻译失败:'.$trans_err['error_msg'] ?? '');
                                    }else{
                                        $update_goods_data[$t_field] = implode("\n", $trans_res);
                                        // 记录翻译前的原始数据
                                        $update_goods_data['origional_'.$t_field] = $goods_info[$t_field];
                                    }
                                }
                            }
                        }
                    }
                    if(!empty($update_goods_data)){
                        $count = OzonGoodsModel::mq()->where(['id' => $goods_info['id']])->update($update_goods_data);
                    }
                    // 提交事务
                    Db::commit();
                } catch (\Exception $th) {
                    Db::rollback();
                    $this->error('商品SPU:'.$goods_info['spu_code'].'更新翻译失败,error:'.$th->getMessage());
                }
            }
            $this->success('翻译成功');
        }else{
            // 翻译列表
            $langList = SystemBase::mk()->items('翻译语言列表');
            // 获取需要翻译的模块
            $transfer_data = GoodsModel::getTranslatePart();
            $transfer_extra_data = $transfer_data['extra'] ?? [];
            // 需要操作的列表数据
            $goods_ids = $this->request->get('id', '');
            if(empty($goods_ids)){
                $this->error('请选择需要翻译的商品');
            }
            $shop_account = $this->account_id ?? 0;
            // 获取可选翻译部分
            $this->fetch('translate', ['langList' => $langList, 'transfer_extra' => $transfer_extra_data, 'goods_ids' => $goods_ids
            , 'platform_id' => $this->platform_id, 'shop_account' => $shop_account]);
        }
    }

    /**
     * 删除
     * @auth true
     * @menu true
     * @return void
     */
    public function delete()
    {
        $id = $this->request->param('id', 0);

        $info = OzonGoodsModel::mq()->find($id);
        if(!$info) {
            $this->error('产品信息错误');
        }
        try {
            $result = OzonGoodsModel::mq()->where(['id' => $id])->update(['is_deleted' => 1]);
            if(!$result){
                throw new \Exception(lang('删除失败'));
            }
        } catch (\Exception $e) {
            $this->error(lang('删除失败'));
        }
        $this->success(lang('删除成功'));
    }



    /**
     * 推送商品
     *
     * @return void
     */
    public function pushGoods ()
    {
        $ids = $this->request->post('ids', '');
        if(empty($ids)){
            $this->error('请选择需要推送的商品');
        }
        $ids_arr = explode(',', $ids);

        $sync_goods_service = new SyncGoodService();

        $ret = $sync_goods_service->pushGoods($ids_arr, 'ozon');
        if(empty($ret['code']) || ($ret['code'] != 1)){
            $this->error($ret['msg']);
        }

        $this->success('推送成功');
    }

    /**
     * 获取分类列表
     * @return void
     */
    public function getCategoryList()
    {
        // 获取平台分类
        $list = OzonGoodsCategoryModel::getCategoryTree();
        if(!empty($list)) {
            $this->success('分类树列表', $list);
        }
        $list = OzonGoodsCategoryModel::mk()->where(['status' => 0])->order('level')->field('name title,id,pid,path,type_id')->select()->toArray();
        $list = OzonGoodsCategoryModel::categoryTree($list);
        $this->success(lang('分类列表'), $list);
    }


    public function getFeatureList()
    {
        $category_id = $this->request->param('category_id', 0);
        // 获取品台分类属性
        $list = OzonGoodsFeatureModel::getFeatureList($category_id);
        $spec_list = [];
        foreach($list as $key => $value) {
            if($value['is_aspect'] == 1) {
                $spec_list[$value['feature_id']] = [
                    'featureValue' => $value['featureValue'],
                    'name' => $value['name'],
                    'input_type' => $value['input_type'],
                    'feature_id' => $value['feature_id'],
                    'is_required' => $value['is_required'],
                    'is_collection' => $value['is_collection'],
                ];
                unset($list[$key]);
            }
        }
        $this->success(lang('属性特征列表'), ['list' => $list, 'spec_list' => $spec_list]);
    }




    /**
     * 根据分类ID获取属性列表
     * @return void
     */
    public function getBrandByPages()
    {
        $description_category_id = $this->request->param('description_category_id', 0); // 分类父级ID
        $type_id = $this->request->param('type_id', 0); // 分类ID
        $shop_id = $this->request->param('shop_id', 0);
        $ozon_goods_model = new OzonGoodsModel();
        $data = $ozon_goods_model->getBrandByPages($shop_id, $description_category_id, $type_id);
        if($data['code'] == 1) {
            // 处理列表数据
            $required_list = $no_required_list = $attr_ids = $attr_spec_list = [];
            foreach ($data['data'] as $key => $item) { // 将必填的放在最前面
                if($item['is_required'] === true) {
                    $required_list[] = $item;
                } else {
                    $no_required_list[] = $item;
                }
                // 需要获取属性值的集合
                if($item['is_collection'] === true) {
                    $attr_ids[] = $item['id'];
                }
                // 需要再规格列表中映射的属性
                if($item['is_aspect'] === true) {
                    $attr_spec_list[] = $item;
                    unset($data['data'][$key]);
                }
            }
            $data['data'] = array_merge($required_list, $no_required_list);
            unset($required_list);
            unset($no_required_list);

            // 获取属性
//            if(!empty($attr_ids)) {
//                $attr_value_list = [];
//                foreach ($attr_ids as $key => $item) {
//                    $result = $ozon_goods_model->getAttrValue($shop_id, $item, $description_category_id, $type_id);
//                    $attr_value_list[$item] = $result['data'];
//                }
//                halt($attr_value_list);
//            }

            $this->success(lang('属性列表'), ['list' => $data['data'], 'attr_spec_list' => $attr_spec_list]);
        } else {
            $this->error($data['msg']);
        }
    }

    public function getAttrValue()
    {
        $description_category_id = $this->request->param('description_category_id', 0); // 分类父级ID
        $category_id = $this->request->param('category_id', 0); // 属性ID
        $type_id = $this->request->param('type_id', 0); // 分类ID
        $shop_id = $this->request->param('shop_id', 0);
        $ozon_goods_model = new OzonGoodsModel();
        $data = $ozon_goods_model->getAttrValue($shop_id, $category_id, $description_category_id, $type_id);
        if($data['code'] == 1) {
            $this->success(lang('属性值列表'), $data['data']);
        } else {
            $this->error($data['msg']);
        }
    }

    /**
     * 获取推送错误信息
     * @Description
     * @author wangqinghui
     * @date 2024-12-16 11:35
     * @return void
     */
    public function pushErrorList()
    {
        $goods_id = (int)$this->request->post('id', 0);
        if(empty($goods_id) || ($goods_id <= 0)){
            $this->error('商品ID参数错误');
        }
        $page = (int)$this->request->post('page', 1);
        $limit = (int)$this->request->post('limit', 10);
        $map = [
            ['goods_id', '=', $goods_id]
        ];
        $offer_ids = OzonGoodsSkuModel::mk()->where($map)->column('goods_nu');
        $list = [];
        $total = 0;
        if(!empty($offer_ids)){
            $map = [
                ['offer_id',    'in', $offer_ids]
            ];
            $total = OzonGoodsPushMsgModel::mk()->where($map)->count();
            $field = 'id,type,task_id,offer_id,message,description,level,create_at';
            $list = OzonGoodsPushMsgModel::mk()->field($field)->where($map)->page($page,$limit)->order(['id' => 'desc'])->select()->toArray();
            if(!empty($list)){
                $type_arr = OzonGoodsPushMsgModel::getTypeArr();
                foreach($list as $key => $val){
                    $list[$key]['type_text'] = !empty($type_arr[$val['type']]) ? $type_arr[$val['type']] : '未知';
                }
            }
        }
        $this->success('获取成功', ['item' => $list, 'total' => $total], 0);
    }

    /**
     * 获取ozon仓库列表
     * @Description
     * @author wangqinghui
     * @date 2024-12-23 17:15
     * @return void
     */
    public function getOzonWarehouseList()
    {
        $account_id = (int)$this->request->post('account_id', 0);
        $shop_id = (int)$this->request->post('shop_id', 0);
        $goods_id = (int)$this->request->post('goods_id', 0);
        if(empty($goods_id) || ($goods_id <= 0)){
            $this->error('商品参数错误');
        }
        // 获取商品SKU列表
        $map = [
            ['goods_id', '=', $goods_id],
        ];
        $field = 'id,goods_nu,attribute_titles,goods_id';
        $goods_sku_list = OzonGoodsSkuModel::mk()->with('stockData')->field($field)->where($map)->select()->toArray();
        $where = [
            ['status', '=', 'created'],
        ];
        if(!empty($account_id)){
            $where[] = ['account_id', '=', $account_id];
        }
        if(!empty($shop_id)){
            $where[] = ['shop_id', '=', $shop_id];
        }
        $field = 'id,account_id,shop_id,warehouse_id,name,status';
        $warehouse_data = OzonWarehouseModel::mk()->where($where)->column($field, 'warehouse_id');
        if(!empty($goods_sku_list)){
            foreach ($goods_sku_list as $key => $sku_info){
                $stock_data = array_column($sku_info['stockData'], 'stock', 'warehouse_id');
                unset($goods_sku_list[$key]['stockData']);
                foreach ($warehouse_data as $warehouse_id => $warehouse_info){
                    $stock = !empty($stock_data[$warehouse_id]) ? $stock_data[$warehouse_id] : 0;
                    $goods_sku_list[$key]['stockData'][$warehouse_id] = [
                        'warehouse_id' => $warehouse_id,
                        'warehouse_name' => $warehouse_info['name'],
                        'stock' => $stock
                    ];
                }
            }
        }
        $this->success('获取成功', ['total' => count($goods_sku_list), 'item' => $goods_sku_list], 0);
    }

    /**
     * 设置库存
     * @auth true
     * @Description
     * @author wangqinghui
     * @date 2024-12-24 16:11
     * @return void
     */
    public function setInventory()
    {
        if($this->request->isPost()){
            $post_data = $this->request->post('sku_data');
            $account_id = (int)$this->request->post('account_id', 0);
            $shop_id = (int)$this->request->post('shop_id', 0);
            if(empty($post_data)){
                $this->error('提交数据不能为空');
            }
            if(empty($account_id) || ($account_id <= 0)){
                $this->error('账号参数错误');
            }
            if(empty($shop_id) || ($shop_id <= 0)){
                $this->error('店铺参数错误');
            }
            $sku_data = json_decode($post_data, 1);
            if(empty($sku_data)){
                $this->error('提交数据不能为空');
            }
            // 获取sku库存
            $map = [
                ['goods_id', '=', $sku_data[0]['goods_id']]
            ];
            $field = 'id,goods_id,goods_nu,warehouse_id,stock,push_status';
            $old_sku_stock_list = OzonGoodsSkuStockModel::mk()->field($field)->where($map)->select()->toArray();
            $old_sku_stock_data = [];
            if(!empty($old_sku_stock_list)){
                foreach ($old_sku_stock_list as $key => $value) {
                    $old_sku_stock_data[$value['goods_nu']][$value['warehouse_id']] = $value;
                }
            }
            
            $sku_rule = [
                'goods_id|商品ID' => 'require|integer|>:0',
                'goods_nu|商品货号' => 'require',
            ];
            $validate = Validate::rule($sku_rule);
            $add_data = [];
            foreach ($sku_data as $key => $sku_info){
                if (!$validate->check($sku_info)) {
                    $this->error($validate->getError());
                }
                $stock_list = !empty($sku_info['stock_list']) ? $sku_info['stock_list'] : [];
                if(empty($stock_list)){
                    $this->error($sku_info['goods_nu'].'请至少设置一个仓库库存');
                }
                $stock_data = !empty($old_sku_stock_data[$sku_info['goods_nu']]) ? $old_sku_stock_data[$sku_info['goods_nu']] : [];
                $warehouse_data = !empty($sku_info['stockData']) ? $sku_info['stockData'] : [];
                foreach($stock_list as $warehouse_id => $stock){
                    if(empty($warehouse_id) || ($warehouse_id <= 0)){
                        $this->error($sku_info['goods_nu'].'仓库ID参数错误');
                    }
                    if(!ctype_digit((string) $stock)){
                        $this->error($sku_info['goods_nu'].'库存数量必须是数字');
                    }
                    if(($stock < 0) || ($stock > 1000000)){
                        $this->error($sku_info['goods_nu'].'库存数量在0-1000000之间');
                    }
                    $warehouse_name = !empty($warehouse_data[$warehouse_id]['warehouse_name']) ? $warehouse_data[$warehouse_id]['warehouse_name'] : '';
                    if(!empty($stock_data[$warehouse_id]['push_status']) && ($stock_data[$warehouse_id]['push_status'] == 1)){
                        $this->error($sku_info['goods_nu'].'仓库:'.$warehouse_name.'库存未更新,请同步库存');
                    }
                    if(empty($stock)){
                        unset($sku_data[$key]['stock_list'][$warehouse_id]);
                    }
                }
            }
            // 启动事务
            Db::startTrans();
            try {
                foreach ($sku_data as $key => $sku_info){
                    $stock_list = !empty($sku_info['stock_list']) ? array_filter($sku_info['stock_list']) : [];
                    $stock_data = !empty($old_sku_stock_data[$sku_info['goods_nu']]) ? $old_sku_stock_data[$sku_info['goods_nu']] : [];
                    $del_stock_data = array_diff_key($stock_data, $stock_list);
                    if(!empty($del_stock_data)){
                        OzonGoodsSkuStockModel::mk()->whereIn('id', array_column($del_stock_data, 'id'))->delete();
                    }
                    foreach($stock_list as $warehouse_id => $stock){
                        $temp = [
                            'account_id'    => $account_id,
                            'shop_id'       => $shop_id,
                            'goods_id'      => $sku_info['goods_id'],
                            'goods_nu'      => $sku_info['goods_nu'],
                            'warehouse_id'  => $warehouse_id,
                            'stock'         => $stock,
                        ];
                        $old_stock_id = !empty($stock_data[$warehouse_id]['id']) ? $stock_data[$warehouse_id]['id'] : 0;
                        if(!empty($old_stock_id)){
                            OzonGoodsSkuStockModel::mk()->where('id', $old_stock_id)->update($temp);
                        }else{
                            $add_data[] = $temp;
                        }
                    }
                }
                if(!empty($add_data)){
                    OzonGoodsSkuStockModel::mk()->insertAll($add_data);
                }
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error('库存设置失败:'.$e->getMessage());
            }
            $this->success('设置库存成功');
        }else{
            $goods_id = (int)$this->request->get('id', 0);
            if(empty($goods_id) || ($goods_id <= 0)){
                $this->error('商品ID参数错误');
            }
            // 获取商品信息
            $field = 'id,account_id,shop_id';
            $goods_info = OzonGoodsModel::mk()->field($field)->where(['id' => $goods_id])->find();
            if(empty($goods_info)){
                $this->error('商品不存在');
            }
            $this->fetch('set_inventory', ['goods_info' => $goods_info]);
        }
    }

    /**
     * 推送商品库存
     * @auth true
     * @Description
     * @author wangqinghui
     * @date 2024-12-26 16:05
     * @return void
     */
    public function syncStock()
    {
        $ids = $this->request->post('ids', '');
        if(empty($ids)){
            $this->error('请选择需要同步库存的商品');
        }

        $ids_arr = explode(',', $ids);
        $sync_goods_service = new SyncGoodService();
        $ret = $sync_goods_service->pushGoodsStock($ids_arr, 'ozon');

        if(empty($ret['code']) || ($ret['code'] != 1)){
            $this->error($ret['msg']);
        }

        $this->success('同步库存成功');
    }

    /**
     * 同步ozon库存
     * @auth true
     * @Description
     * @author wangqinghui
     * @date 2024-12-28 16:17
     * @return void
     */
    public function pullSingleGoodsStock()
    {
        $sku_ids = $this->request->post('sku_ids', '');
        if(empty($sku_ids)){
            $this->error('请选择要同步库存的SKU');
        }
        $sku_ids_arr = explode(',', $sku_ids);
        // 获取商品ozonsku
        $map = [
            ['id', 'in', $sku_ids_arr]
        ];
        $field = 'id,goods_id,goods_nu,product_id,ozon_sku';
        $sku_data = OzonGoodsSkuModel::mk()->field($field)->where($map)->select()->toArray();
        if(empty($sku_data)){
            $this->error('要同步库存的SKU信息有误');
        }
        $ozon_sku_data = array_column($sku_data, 'ozon_sku');
        if(empty($ozon_sku_data)){
            $this->error('同步库存失败,没有ozonsku');
        }
        // 获取商品信息
        $goods_id = !empty($sku_data[0]['goods_id']) ? $sku_data[0]['goods_id'] : 0;
        $goods_info = OzonGoodsModel::mk()->where('id', $goods_id)->find();
        if(empty($goods_info)){
            $this->error('同步库存失败,没有商品信息');
        }
        // 获取店铺信息
        $field = 'id,name,client_id,api_key';
        $shop_info = ShopsModel::mk()->field($field)->where('id', $goods_info['shop_id'])->find();
        if(empty($shop_info)){
            $this->error('同步库存失败,没有店铺信息');
        }
        
        $ozon_config = [
            'client_id'     =>  $shop_info['client_id'],
            'api_key'       =>  $shop_info['api_key'],
        ];
        try {
            $ozon_client = new Ozon($ozon_config);
        } catch (\Exception $th) {
            $this->error('同步库存失败:'.$th->getMessage());
        }
        $stock_ret = $ozon_client->getStocksInfo($ozon_sku_data);
        if(empty($stock_ret['code']) || ($stock_ret['code'] == 0)){
            $this->error('同步库存失败:'.$ozon_client->getErr());
        }

        $stock_data = !empty($stock_ret['data']['result']) ? $stock_ret['data']['result'] : [];
        if(empty($stock_data)){
            $update_data = ['stock' => 0, 'ozon_stock' => 0, 'ozon_reserved_stock' => 0, 'push_status' => 2];
            OzonGoodsSkuStockModel::mk()->where('goods_id', $goods_id)->update($update_data);
        }else{
            $ozon_product_id_arr = array_column($sku_data, 'goods_nu', 'product_id');
            foreach ($stock_data as $key => $value) {
                $goods_nu = !empty($ozon_product_id_arr[$value['product_id']]) ? $ozon_product_id_arr[$value['product_id']] : '';
                if(!empty($goods_nu)){
                    $map = [
                        ['goods_id',        '=', $goods_id],
                        ['goods_nu',        '=', $goods_nu],
                        ['warehouse_id',    '=', $value['warehouse_id']]
                    ];
                    $update_data = ['stock' => $value['present'], 'ozon_stock' => $value['present'], 'ozon_reserved_stock' => $value['reserved'], 'push_status' => 2];
                    OzonGoodsSkuStockModel::mk()->where($map)->update($update_data);
                }
            }
        }
        $this->success('同步库存成功');
    }
}